package com.kx.demo.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * @author kx
 * @date 2020/4/12
 */
public class VolatileDemo {

    static volatile int flag = 0;
    //    static int flag = 0;

    public static void main(String[] args) {


        new Thread(){
            @Override
            public void run() {
                int localFlag = flag;
                while (true) {
                    if (localFlag != flag) {
                        System.out.println("=====感知到=====flag变量发生变化:" + flag);
                        localFlag = flag;
                    }
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                try {
                    while (true) {
                        System.out.println("修改了flag值:" + ++flag);
                        TimeUnit.SECONDS.sleep(1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

}
